package com.hpradip.android.documentaryHub;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

public class SearchableActivity extends Showcase {

	private ProgressDialog progressDialog;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		Intent intent = getIntent();
		if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
			String query = intent.getStringExtra(SearchManager.QUERY);

			searchFeeds(query);
		}
	}
	
	@Override
	protected void onNewIntent(Intent intent) {
		if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
			String query = intent.getStringExtra(SearchManager.QUERY);

			searchFeeds(query);
		}
		super.onNewIntent(intent);
	}

	@Override
	protected void onResume() {

		super.onResume();
	}

	private void searchFeeds(final String query) {
		Runnable feedSearchable = new Runnable() {

			public void run() {
				searchResults = new ArrayList<DocumentaryFeed>();
				String lowerCaseQuery = query.trim().toLowerCase();
				List<DocumentaryFeed> feeds = DataProvider.documentaryFeeds;
				for (DocumentaryFeed documentaryFeed : feeds) {

					if (documentaryFeed.getTitle().toLowerCase()
							.contains(lowerCaseQuery)
							|| documentaryFeed.getCategory().toLowerCase()
									.contains(lowerCaseQuery))
						searchResults.add(documentaryFeed);
				}

				handler.sendEmptyMessage(0);
			}

			private Handler handler = new Handler() {
				@Override
				public void handleMessage(Message msg) {
					setListAdapter(new FeedsAdapter(SearchableActivity.this,
							R.layout.list_item2, searchResults));
					progressDialog.dismiss();
				}
			};
		};

		new Thread(feedSearchable, "FeedSearcher").start();
		progressDialog = ProgressDialog.show(this, "Please wait",
				"Searching documentaries", true);
	}

}
